package manager.rank;

import net.socket.server.request.LocalPlayResultRequest;
import redis.clients.jedis.Jedis;
import util.MyFactory;
import util.RedisUtil;

public class InsertToRedis {
	private Jedis myJedis =null;

	/**
	 * 插入redis并且返回本次唱歌的单曲排名
	 * @param req
	 */
	@SuppressWarnings("finally")
	public int[]  insertRedisSongRankAndReturnThisRank(LocalPlayResultRequest req) {
		String mid = Integer.toString(req.getMachineId());
		String songId = req.getSongId();
		String openId = req.getOpenId();
		int [] ranks= new int[2];
		int score = req.getScore();
		double beforeScore;
		 try {
			 myJedis = MyFactory.context.getBean("RedisUtil", RedisUtil.class).getJedis();
			 myJedis.zincrby("vod:SingTimesRank", 1, openId);//唱歌次数的排行榜(总榜）
			 myJedis.zincrby("vod:SingTimesRank:" + mid, 1, openId);//唱歌次数排行榜（机器榜）
			 
			 //唱过的歌曲排行榜（唱了多少首不同的歌）
			 //判断songId是不是已经被openId唱过，如果没唱过，加入set里面，并且在sorted set里面将对应的openId唱过的歌曲数加1
			 if(myJedis.sismember("vod:SingSongSet:"+openId, songId)==false ) {
				 myJedis.sadd("vod:SingSongSet:"+openId, songId);
				 myJedis.zincrby("vod:SongNumRank", 1, openId);
			 }
			 //单机榜
			 if(myJedis.sismember("vod:SingSongSet:"+openId+":"+mid, songId)==false ) {
				 myJedis.sadd("vod:SingSongSet:"+openId+":"+mid, songId);
				 myJedis.zincrby("vod:SongNumRank:"+mid, 1, openId);
			 }
			 
			 //单曲得分榜:如果为null，表示此人以前没唱过这首歌，则将其放入，此时返回的排名就是本次的排名
			 if(null == myJedis.zscore("vod:SingleSongScoreRank:"+songId, openId)){
				 myJedis.zadd("vod:SingleSongScoreRank:"+songId, score, openId);
				 ranks[0] = myJedis.zrevrank("vod:SingleSongScoreRank:"+songId, openId).intValue()+1;
			 }else{
				beforeScore = myJedis.zscore("vod:SingleSongScoreRank:"+songId, openId);
				 myJedis.zadd("vod:SingleSongScoreRank:"+songId, score, openId);
				 ranks[0] = myJedis.zrevrank("vod:SingleSongScoreRank:"+songId, openId).intValue()+1+1;
				 //如果以前的最大分数大于本次的，还要将以前的分数换回去
				 if(beforeScore >(double)score) 
					 myJedis.zadd("vod:SingleSongScoreRank:"+songId, beforeScore, openId);
				 else
					ranks[0]--;
				
			 }
			 //单机榜，如果不等于null，则只有当以前的分数小于本次的才放到redis里
			 if(null ==myJedis.zscore("vod:SingleSongScoreRank:"+songId+":"+mid, openId)) {
				myJedis.zadd("vod:SingleSongScoreRank:"+songId+":"+mid, score, openId);	
				ranks[1] = myJedis.zrevrank("vod:SingleSongScoreRank:"+songId+":"+mid,  openId).intValue()+1;
			 }else {
				 beforeScore = myJedis.zscore("vod:SingleSongScoreRank:"+songId+":"+mid, openId);
				 myJedis.zadd("vod:SingleSongScoreRank:"+songId+":"+mid, score, openId);
				 ranks[1] = myJedis.zrevrank("vod:SingleSongScoreRank:"+songId+":"+mid,  openId).intValue()+1+1;
				 if(beforeScore <(double)score) 
					 myJedis.zadd("vod:SingleSongScoreRank:"+songId+":"+mid, score, openId);
				 else
					 ranks[1]--;
			 }
			 
			 
		} catch (Exception e) {
			System.out.println("insertRedis get a Exception---"+e);
		}finally {
			if(null != myJedis)
				myJedis.close(); // 释放资源还给连接池
			return ranks;
		}
		
	}
}
